<template>
  <div class="autn">
    <div class="imgBox" v-if="Sign == false">
      <img class="fadelogIn" v-if="cover != ''" :src="cover" alt="" />
      <div class="xgplayer-icon-play icon_player" @click="playerCom()">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="70"
          height="70"
          viewBox="0 0 70 70"
        >
          <path
            transform="translate(15,15) scale(0.04,0.04)"
            d="M576,363L810,512L576,661zM342,214L576,363L576,661L342,810z"
          ></path>
        </svg>
      </div>
    </div>
    <div v-show="Sign == true" ref="video" id="mmid"></div>

    <Login ref="login" />
    <a-modal
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <template slot="title">
        <div class="cOicon-id">
          <img class="imgagesFour" src="@/assets/image/sigh.png" alt="" />
          <span class="yelloTxt">提示信息</span>
        </div>
      </template>
      <div class="tip">
        <span class="span1">
          恭喜您，当前课程内容已全部学完，进度显示为100%，为您颁发课程证书!
        </span>

        <img
          class="image1"
          style="height: 120px"
          :src="imageWebUrl + dataurl"
          alt=""
        />
        <span class="image1" @click="visible = false">我知道了</span>
      </div>
    </a-modal>


    <dir id="bgvid" v-show="0"></dir>
  </div>
</template>

<script type="text/ecmascript-6">
import Player from "xgplayer";
import HlsJsPlayer from "xgplayer-hls";
import "../../.xgplayer/skin/index.js";
import * as api from "@/api/employment";
import Login from "@/components/popup/login/index.vue";
import { apisaveVideo, selCertificate, totalrate } from "../api/employment";
export default {
  props: {
    url: {
      type: String,
      required: true,
      default: "",
    },
    width: {
      type: Number,
      required: false,
      default: 500,
    },
    height: {
      type: Number,
      required: false,
      default: 500,
    },

    isPlay: [String, Number],
    videoTime: [String, Number],
    courseNo: [String, Number],
    // 当前的视频id
    notice: {
      type: String,
      required: false,
      default: 500,
    },
    // 最后一条视频的id
    endid: {
      type: String,
      required: true,
      default: 500,
    },
    // 当前播放的视频id
    nowvideoId: {
      type: String,
      required: true,
      default: 500,
    },
  },
  data() {
    return {
      first: false,
      videoPlayer: null,
      videoUrl: this.url,
      courseNos: this.courseNo,
      time: null,
      Sign: false,
      cover: "",
      titleChanged: true,
      certificateimg: "",
      // 弹窗部分
      ModalText: "Content of the modal",
      visible: false,
      confirmLoading: false,
      // 所渲染图片
      dataurl: "",
      videoTimes: this.$route.query.learnedTime,
    };
  },
  watch: {
    url(val) {
      this.videoUrl = val;
      if (this.videoPlayer != null) {
        this.videoPlayer.src = val;
      }
      this.$forceUpdate();
    },
    courseNo(val) {
      this.courseNos = val;
    },
  },
  components: {
    Login,
  },
  created() {
    // this.videoUrl = this.url
  },
  mounted() {
    this.getVideo(this.courseNos, this.catalogueCodes, this.videoCodes);
    // this.videoPlayer && typeof this.videoPlayer.destroy === 'function' && this.videoPlayer.destroy();
    if (this.$store.state.token != "") {
      this.Sign = true;
    }
  },
  methods: {
    getVideo(courseNos, catalogueCodes, videoCodes) {
      let selt = this;
      this.$ajax({
        url: "/educational/courseinfo/get/detail?courseNo=" + courseNos,
        method: "post",
        params: {},
      }).then((res) => {
        if (res.code == 200) {
          if (res.data.catalogueFlag == "Y") {
            if (this.$route.query.my == "1") {
              if (res.data.courseNo == this.$route.query.courseNo) {
                res.data.catalogue.forEach((itme, index) => {
                  itme.children.forEach((children, childrenIndex) => {
                    if (children.cataNo == this.$route.query.videoCode) {
                      this.videoUrl = this.imageWebUrl + children.filePath;
                    }
                  });
                });
              }
            } else {
              this.videoUrl =
                this.imageWebUrl + res.data.catalogue[0].children[0].filePath;
            }
          } else {
            this.videoUrl = this.imageWebUrl + res.data.catalogue.filePath;
          }
          this.cover = this.imageWebUrl + res.data.cover;
          if (this.videoUrl.indexOf("m3u8") != -1) {
            this.videoPlayer = new HlsJsPlayer({
              el: document.querySelector("#mmid"),
              url: this.videoUrl,
              // url: 'http://192.168.10.215:8080/live/livestream.m3u8',
              // url: "http://192.168.10.215:8080/live/livestream.flv",
              width: this.width,
              height: this.height,
              volume: 0.6, // 初始音量
              autoplay: true, // 自动播放
              playsinline: true,
              lastPlayTime: this.videoTimes, //视频起播时间（单位：秒）
              cors: true,
              crossOrigin: true,
              poster: this.cover,
              "x5-video-player-type": "h5",
              "x5-video-player-fullscreen": false,
              download: false, //设置download控件显示
              playbackRate: this.isPlay == "1" ? [1, 1.5, 2] : [],
              defaultPlaybackRate: 1,
              ignores: this.isPlay == "1" ? [] : ["progress"],
              // fitVideoSize: 'auto'
            });
          } else {
            this.videoPlayer = new Player({
              el: document.querySelector("#mmid"),
              url: this.videoUrl,
              // url: 'http://192.168.10.215:8080/live/livestream.m3u8',
              // url: "http://192.168.10.215:8080/live/livestream.flv",
              width: this.width,
              height: this.height,
              volume: 0.6, // 初始音量
              autoplay: this.Sign ? true : false, // 自动播放
              playsinline: true,
              lastPlayTime: this.videoTimes, //视频起播时间（单位：秒）
              cors: true,
              crossOrigin: true,
              poster: this.cover,
              "x5-video-player-type": "h5",
              "x5-video-player-fullscreen": false,
              download: false, //设置download控件显示
              playbackRate: this.isPlay == "1" ? [1, 1.5, 2] : [],
              defaultPlaybackRate: 1,
              ignores: this.isPlay == "1" ? [] : ["progress"],
              // fitVideoSize: 'auto'
            });
          }
          // this.videoPlayer.emit('resourceReady',
          //   [
          //     { name: '超清', url: this.videoUrl },
          //     { name: '高清', url: this.videoUrl },
          //     { name: '标清', url: this.videoUrl }
          //   ]);
          //播放时常改变的方法
          this.videoPlayer.on("timeupdate", function (res) {
            // console.log(res)
            // console.log(res.duration)
            //事件名称可以在上述查询
            this.time = "";
            // 当前播放进度
            this.time = res.currentTime;
            // console.log(this.time)
            // 剩余时间小于5秒，触发生成证书
            // if(res.duration != NaN){
            //   if((res.duration - this.time) < 5 && !this.first){
            //     let params = {
            //       courseNo: selt.notice,
            //     };
            //     if (selt.nowvideoId === selt.endid) {
            //       api.selCertificate(params).then((res) => {
            //         if (res.code==200) {
            //           selt.dataurl = res.data;
            //           selt.visible = true;
            //         } else {
            //           console.log("已生成");
            //         }
            //         return;
            //       });
            //     } else {
            //       console.log("不是");
            //     }
            //     this.first = true
            //   }
            // }
          });
          //播放完毕
          this.videoPlayer.on("ended", function (res) {
            // 观看完毕，生成证书，判断当前的播放视频是否是最后的一条视频，判断当前视频进度条达到100时调用
            // console.log(this.$refs.VideoPlayer.titleChanged);
            let totalrateParams = {
              courseNo: courseNos,
              catalogueCode: sessionStorage.getItem("pcataNo"),
              videoCode: sessionStorage.getItem("cataNo"),
              learnedTime: this.time,
            };
            api.totalrate(totalrateParams).then((res) => {
              console.log(res.data.totalRate, "郁闷");
              if (res.data.totalRate == "01") {
                let params = {
                  courseNo: selt.notice,
                };
                api.selCertificate(params).then((res) => {
                  if (res.code == 200) {
                    selt.dataurl = res.data;
                    selt.visible = true;
                  } else {
                    return true
                    // console.log("已生成");
                    // selt.$message.error(res.msg);
                  }
                  return;
                });
              }
            });
            // let params = {
            //   courseNo: selt.notice,
            // };
            // if (selt.nowvideoId === selt.endid) {
            //   api.apisaveVideo(params).then((res) => {
            //     if (res.code==200) {
            //       selt.dataurl = res.data;
            //       selt.visible = true;
            //     } else {
            //       console.log("已生成");
            //       selt.$message.error(res.msg);
            //     }
            //     return;
            //   });
            // } else {
            //   console.log("不是");
            // }
          });
          //视频结束获取时常调接口
          this.videoPlayer.on("pause", function () {
            // console.log("asdasd", this.time);
            if (this.time > 0.9) {
              var params = {
                courseNo: courseNos,
                catalogueCode: sessionStorage.getItem("pcataNo"),
                videoCode: sessionStorage.getItem("cataNo"),
                learnedTime: this.time,
              };
              api.apisaveVideo(params).then((res) => {
                this.time = "";
              });
            }
          });
        } else {
        }
      });
      // var video = document.getElementById("mmid");
      // window.URL = window.URL || window.webkitURL;
      // var xhr = new XMLHttpRequest();
      // var play_url = this.url;
      // xhr.open("GET", play_url, true);
      // xhr.responseType = "blob";
      // xhr.onload = function() {
      // 	if (this.status == 200) {
      // 		var blob = this.response;
      // 		console.log(blob);
      // 		window.URL.revokeObjectURL(play_url);
      // 		console.log(window.URL.createObjectURL(blob))
      // 	}
      // }
      // xhr.send();
    },
    playerCom() {
      if (!this.$store.state.token) {
        this.$refs["login"].tabIndex = 0;
        this.$refs["login"].tabType = 0;
        this.$refs["login"].visible = true;
        this.$refs["login"].maskClosable = true;
      }
      this.$forceUpdate();
      // this.videoPlayer && typeof this.videoPlayer.destroy === 'function' && this.videoPlayer.destroy();
    },
    // 弹框部分
    showModal() {},
    handleOk(e) {
      this.ModalText = "The modal will be closed after two seconds";
      this.confirmLoading = true;
      setTimeout(() => {
        this.visible = false;
        this.confirmLoading = false;
      }, 2000);
    },
    handleCancel(e) {
      // console.log("Clicked cancel button");
      this.visible = false;
    },
  },
  // beforeDestroy() {
  //   this.videoPlayer && typeof this.videoPlayer.destroy === 'function' && this.videoPlayer.destroy();
  // },
  // beforeUpdate() {
  //   this.getVideo(this.courseNos,this.catalogueCodes,this.videoCodes)
  // },
};
</script>
<style lang="less" scoped>
.autn {
  width: 554px;
  min-height: 324px;
  position: relative;
}
.image1 {
  width: 170px;
  margin: 0 auto;
  display: block;
  text-align: center;
  justify-items: center;
  margin-top: 24px;
}
.icon_player {
  position: absolute;
  display: inline-block;
  z-index: 99;
  background: rgba(0, 0, 0, 0.38);
  width: 70px;
  height: 70px;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  border-radius: 50%;
  cursor: pointer;
}
.icon_player svg {
  fill: rgba(255, 255, 255, 0.7);
}
.imgBox {
  position: absolute;
  //min-height: 616px;
  height: 100%;
  /*height: 616px;*/
  width: 554px;
  background: #f5f5f59c;
  img {
    width: 554px;
    height: 324px;
  }
}

.tip {
  height: auto;
}
.yelloTxt {
  margin-left: 10px;
}
.span1 {
  height: 42px;
  font-size: 15px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #333333;
  line-height: 21px;
  display: block;
}

/deep/.ant-modal-footer {
  display: none;
}
</style>
